package za.ac.cput.arrowgame.presentation.desktop;

import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import javax.swing.table.TableColumn;
import za.ac.cput.arrowgame.model.Grid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import za.ac.cput.arrowgame.app.config.GetContext;
import za.ac.cput.arrowgame.app.exceptions.InvalidInput;
import za.ac.cput.arrowgame.app.exceptions.Win;
import za.ac.cput.arrowgame.app.facade.Facade;
import za.ac.cput.arrowgame.app.factories.AppFactory;
import za.ac.cput.arrowgame.service.requesthandler.Command;
import za.ac.cput.arrowgame.service.requesthandler.Handler;
import za.ac.cput.arrowgame.service.requesthandler.HandlerSetup;
import za.ac.cput.arrowgame.service.requesthandler.Request;

/**
 *
 * @author Lance
 */
public class MainFrame extends javax.swing.JFrame {

    private Grid gridModel = new Grid();
    private static Logger logger = LoggerFactory.getLogger(MainFrame.class);

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        GetContext.setApplicationContext(new ClassPathXmlApplicationContext("applicationContext-connection.xml"));
        gridModel.setColumnWidth(64);
        gridModel.setRowHeight(64);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grid = new javax.swing.JTable();
        grid.setRowHeight(gridModel.getRowHeight());
        Enumeration<TableColumn> cols = grid.getColumnModel().getColumns();
        for (; cols.hasMoreElements();) {
            cols.nextElement().setPreferredWidth(gridModel.getColumnWidth());
        }
        commandsLabel = new javax.swing.JLabel();
        commandsTextField = new javax.swing.JTextField();
        goButton = new javax.swing.JButton();
        mainFrameMenuBar1 = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        newGameMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        grid.setModel(gridModel);
        grid.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        grid.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        grid.setTableHeader(null);

        commandsLabel.setText("Enter Commands");

        goButton.setText("GO");
        goButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goButtonActionPerformed(evt);
            }
        });

        fileMenu.setText("File");

        newGameMenuItem.setText("New Game");
        newGameMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newGameMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(newGameMenuItem);

        mainFrameMenuBar1.add(fileMenu);

        editMenu.setText("Edit");
        mainFrameMenuBar1.add(editMenu);

        setJMenuBar(mainFrameMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(grid, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(commandsLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(commandsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(goButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 68, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(grid, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(commandsLabel)
                    .addComponent(commandsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(goButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newGameMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newGameMenuItemActionPerformed
        Integer gridSize = Facade.getInstance().getUserMessageService().showStartNewGameMessage(rootPane);
        logger.debug("User selected grid size {}", gridSize);
        if(gridSize.equals(Integer.valueOf(6))) {
            this.setSize(397, 480);
        } else if(gridSize.equals(Integer.valueOf(9))) {
            this.setSize(594, 675);
        } else if(gridSize.equals(Integer.valueOf(12))) {
            this.setSize(786, 865);
        }
        gridModel.setGridSize(gridSize);
    }//GEN-LAST:event_newGameMenuItemActionPerformed

    private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goButtonActionPerformed
        final HandlerSetup handlerSetup = Facade.getInstance().getHandlerSetup();
        final Handler handler = handlerSetup.createHandler();

        Request request = new Request();
        request.setRequest(commandsTextField.getText());
        request.createCommand();
        List<Command> commands = request.getCommands();
        for (Command command : commands) {
            try {
                gridModel = handler.handleRequest(command, gridModel);
                Thread.sleep(500);
                grid.setModel(gridModel);
            } catch (InvalidInput ex) {
                Facade.getInstance().getUserMessageService().showErrorDialog(rootPane, ex.getMessage());
                gridModel.setArrow(AppFactory.getInstance().createDefaultArrow(gridModel.getColumnCount() - 1));
                grid.setModel(gridModel);
            } catch (ArrayIndexOutOfBoundsException ex) {
                Facade.getInstance().getUserMessageService().showErrorDialog(rootPane, "Cannot move off grid");
            } catch (Win ex) {
                Facade.getInstance().getUserMessageService().showMessageDialog(rootPane, ex.getMessage());
            } catch (InterruptedException ex) {
                java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_goButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel commandsLabel;
    private javax.swing.JTextField commandsTextField;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JButton goButton;
    private javax.swing.JTable grid;
    private javax.swing.JMenuBar mainFrameMenuBar1;
    private javax.swing.JMenuItem newGameMenuItem;
    // End of variables declaration//GEN-END:variables
}
